package com.party.controller;

import com.party.common.UuidUtils;
import com.party.parBean.FileBean;
import org.json.JSONObject;
import org.ow2.util.base64.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created with IntelliJ IDEA.
 * User: beyond
 * Date: 14-10-15
 * Time: 下午5:37
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/file")
public class CommonController {

    /**
     *
     * @param file
     *            获取要存储的文件
     * @param request
     *            request对象
     * @param response
     *            response对象
     * @return String 返回FileBean对象的信息组装成json格式返回到客户端
     *
     */
    @RequestMapping(value = "/fileUpload")
    public void uploadFiles(@RequestParam MultipartFile file,
                            HttpServletRequest request,
                            HttpServletResponse response)
    {
        FileBean fileBean = new FileBean();
        if (file == null)
        {
            fileBean.setCode("FILE_FAIL_CODE");
        }

        /**
         * 文件唯一标识，UUID
         */
        String UUID = UuidUtils.getUUID();

        Long fileSize = file.getSize();
        String originalFilename = file.getOriginalFilename();
        String base64_name =
                new String(Base64.encode(originalFilename.getBytes()));

        Integer index = originalFilename.lastIndexOf(".");
        String filePrefix = originalFilename;
        String fileSuffix = "";
        if (index != -1)
        {
            filePrefix = originalFilename.substring(0, index);
            fileSuffix = originalFilename.substring(index + 1);
        }

        /**
         * 编码后的文件名
         */
        String fileName = UUID + "_" + base64_name;
        String webSrc = (this.getClass().getClassLoader().getResource("").getPath().toString()).replace("WEB-INF/classes/", "");
        String terminatedPath =webSrc+"/upload/files/";

        /**
         * 临时文件夹
         */
        File dirPath = new File(terminatedPath);

        /**
         * 临时文件路径
         */
        String fileURL = terminatedPath + fileName;

        /**
         * 文件信息
         */
        fileBean.setUUID(UUID);
        fileBean.setOriginalFileName(originalFilename);
        fileBean.setFileName(fileName);
        fileBean.setFilePrefix(filePrefix);
        fileBean.setFileSuffix(fileSuffix);
        fileBean.setFileSize(fileSize);

        if (!dirPath.exists())
        {
            dirPath.mkdirs();
        }
        try
        {
            FileCopyUtils.copy(file.getBytes(), new File(fileURL + "." +
                    fileSuffix));
            fileBean.setCode("FILE_SUCCESS_CODE");
        }
        catch (IOException e)
        {
            fileBean.setCode("FILE_FAIL_CODE");
            e.printStackTrace();
        }
        String json =
                "{\"code\":\"" + fileBean.getCode() + "\",\"UUID\":\"" + UUID +
                        "\",\"originalFilename\":\"" +
                        fileBean.getOriginalFileName() + "\",\"fileName\":\"" +
                        fileName + "\",\"filePrefix\":\"" + filePrefix +
                        "\",\"fileSuffix\":\"" + fileSuffix +
                        "\",\"fileSize\":" + fileSize + "}";
        PrintWriter out = null;
        try
        {
            out = response.getWriter();
            out.write(json);
            out.flush();
            out.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }


    @RequestMapping(value = "/up")
    @ResponseBody
    public String up(
            @RequestParam("file") MultipartFile file
    ) throws IOException {
        if (file == null || file.isEmpty()) {
            return "0";
        }

        String webSrc = (this.getClass().getClassLoader().getResource("").getPath().toString()).replace("WEB-INF/classes/", "");
        String fileDir = "/upload/files/";
        String fileName = file.getOriginalFilename();
        /**
         * 文件唯一标识，UUID
         */
        String UUID = UuidUtils.getUUID();

        File dir = new File(webSrc + fileDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        if (!file.isEmpty()) {
            String preFileName = fileName.substring(0, fileName.lastIndexOf("."));
            String fileType = fileName.substring(fileName.lastIndexOf("."));
            fileName=UUID+fileType;
            File upFile = new File(webSrc + fileDir + fileName);
            FileCopyUtils.copy(file.getBytes(), upFile);
        }
        return fileDir + fileName;
    }

    @RequestMapping("/imageUpload")
    @ResponseBody
    public String imageUpload(
            MultipartHttpServletRequest request
    ) throws Exception {
        //上传图片
        MultipartFile file = request.getFile("imgFile");
        String webSrc = (this.getClass().getClassLoader().getResource("").getPath().toString()).replace("WEB-INF/classes/", "");
        String fileDir = "/upload/images/";
        String fileName = file.getOriginalFilename();
        File dir = new File(webSrc + fileDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        /**
         * 文件唯一标识，UUID
         */
        String UUID = UuidUtils.getUUID();

        if (!file.isEmpty()) {
            String preFileName = fileName.substring(0, fileName.lastIndexOf("."));
            String fileType = fileName.substring(fileName.lastIndexOf("."));
            fileName=UUID+fileType;
            File upFile = new File(webSrc + fileDir + fileName);
            FileCopyUtils.copy(file.getBytes(), upFile);
        }

        JSONObject obj = new JSONObject();
        obj.put("error", 0);
        obj.put("url", fileDir + fileName);
        return obj.toString();
    }


    @RequestMapping("/portraitUpload")
    @ResponseBody
    public String portraitUpload(
            MultipartHttpServletRequest request
    ) throws Exception {
        JSONObject obj = new JSONObject();
        //上传图片
        MultipartFile file = request.getFile("imgFile");
        String webSrc = (this.getClass().getClassLoader().getResource("").getPath().toString()).replace("WEB-INF/classes/", "");
        String fileDir = "/upload/images/";
        String fileName = file.getOriginalFilename();
        File dir = new File(webSrc + fileDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        /**
         * 文件唯一标识，UUID
         */
        String UUID = UuidUtils.getUUID();

        if (!file.isEmpty()) {
            String fileType = fileName.substring(fileName.lastIndexOf("."));
            fileName=UUID+fileType;
            File upFile = new File(webSrc + fileDir + fileName);
            FileCopyUtils.copy(file.getBytes(), upFile);
        }else{
            obj.put("error", 0);
            return obj.toString();
        }

        obj.put("error", 1);
        obj.put("fileName", file.getOriginalFilename());
        obj.put("url", fileDir + fileName);
        return obj.toString();
    }
}
